#!/usr/bin/python
# send images from command line or randomly generated if
# no images are given

import sys
import time
import ImgDist

rate = 4

def read_images(fnames):
    "read image files"
    images = []
    for fname in fnames:
        try:
            img = file(fname).read()
            images.append(img)
        except:
            print "read_images: couldn't open", fname
    return images


def gen_images():
    "generate random image files"
    images = []
    for i in range(30):
        dic = ImgDist.DummyImageCreator()
        dic.draw_dic({'random': 'Image', 'number': i})
        img = dic.get_image() # default format
        images.append(img)
    return images


def loop(lis):
    "generator generating images continuously"
    if not lis:
        return
    i = 0
    length = len(lis)
    while True:
        if i == length:
            i = 0
        yield lis[i]
        i += 1


def main(args):
    global rate
    print "for testing purposes only"
    if not args:
        print "-d to generate dummy images"
        print "otherwise specificy image files on the command line"
        print "-r <rate> for number of images per second, default " + str(rate)
        return
    if "-r" in args:
        idx = args.index("-r")
        rate = int(args[idx+1])
        del args[idx:idx+2] 
    if "-d" in args:
        images = gen_images()
    else:
        images = read_images(args)
    # send the images forever, Ctrl-C to interrupt
    gen = loop(images)
    sender = ImgDist.ImgSenderHTTP()
    try:
        while True:
            img = gen.next()
            print "sending ", len(img)
            sender(img)
            time.sleep(1./float(rate))
    except Exception, data:
        print data
        sender.close()
    

if __name__ == '__main__':
    main(sys.argv[1:])
